import { Service } from 'egg';
import * as crypto from 'crypto';
import axios from 'axios';
import * as queryString from 'querystring';

class AxiosService extends Service {
    /**
     * 生成数据签名
     */
    public async generateSignature(nonce: string, timeStamp: string) {
        const appSecret = this.config.rongyun.appSecret;
        const newStr = appSecret + nonce + timeStamp;
        const hash = crypto.createHash('sha1');
        hash.update(newStr);
        const signature = hash.digest('hex');
        return signature;
    }

    /**
     * 创建axios
     */
    public async createAxios() {
        const nonce = this.ctx.helper.genUUID();
        const timeStamp = (new Date().getTime()).toString();
        const signature = await this.generateSignature(nonce, timeStamp);
        const appKey = this.config.rongyun.appKey;
        const instance = axios.create({
            baseURL: 'http://api.cn.ronghub.com/',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'App-Key': appKey,
                'Nonce': nonce,
                'Timestamp': timeStamp,
                'Signature': signature
            }
        })
        return instance;
    }

    /**
     * 获取token
     */
    public async getCloundToken(param: any) {
        try{
            const axiosTemp = await this.createAxios();
            const submitData: any = {};
            submitData.userId = param.user_id;
            submitData.name = param.user_nickname;
            if (param.url && param.url.length > 0) {
                submitData.portraitUri = this.app.config.baseUrl + param.url;
            } else {
                submitData.portraitUri = this.app.config.baseUrl + '7290495e8ec098466d88.png';
            }
            const result = await axiosTemp.post('user/getToken.json', queryString.stringify(submitData));
            if (result.status === 200) {
                return result.data;
            } else {
                return { code: 2 };
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(JSON.stringify({code:3,msg:e.message}));
        }
    }
}
export default AxiosService;